const app = getApp()
import api from '../../utils/api'
// pages/canteen/canteen.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navBarHeight: app.globalData.navBarHeight, //导航栏高度
    menuBotton: app.globalData.menuBotton, //导航栏距离顶部距离
    menuHeight: app.globalData.menuHeight, //导航栏高度
    // 三餐
    foodType1: [{
        name: '早餐',
        en: 'Breakfast',
        img: '/images/pic_breakfast@2x.png',
        count: 0
      },
      {
        name: '午餐',
        en: 'Lunch',
        img: '/images/pic_lunch@2x.png',
        count: 0
      },
      {
        name: '晚餐',
        en: 'Dinner',
        img: '/images/pic_dinner@2x.png',
        count: 0
      }
    ],
    foodType: null,
    foodTypeIndex: 0,
    foodList: [],


    // list
    interval: 5000,
    duration: 500,
    currentTab: 1, //预设当前项的值
    scrollLeft: 0, //tab标题的滚动条位置
    emptyHidden: true, //无菜单显示背景图
    //日期栏位
    month: 1,
    //日期计算
    DateToBackground: [],
    Date: [],
    Day: [],
    intervalDate: 5000,
    durationDate: 500,
    currentTabDate: 2, //预设当前项的值
    scrollLeftDate: 0, //tab标题的滚动条位置

    tipsDialog: false,
    tipsContent: '',
    // 半屏dialog
    deadline: '', // 订餐截止时间
    isAble: false,
    dialogShow: false,
    foodTotalCount: 0,
    foodTotalAmount: 0,
    promptShow: false,
    canteenOrderId: '',
    fromOrder: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    let foodType = JSON.parse(JSON.stringify(this.data.foodType1))
    this.setData({
      currentTab: options.canteenNo ? options.canteenNo : 1,
      foodType: options.canteenNo == 2 ?  foodType : foodType.slice(0, 2)
    })
    //加载时计算日期
    var theDayBeforeYesterday = new Date()
    theDayBeforeYesterday.setTime(theDayBeforeYesterday.getTime() - 2 * 24 * 60 * 60 * 1000)
    var yesterday = new Date()
    yesterday.setTime(yesterday.getTime() - 1 * 24 * 60 * 60 * 1000)
    var today = new Date()
    var tomorrow = new Date()
    tomorrow.setTime(tomorrow.getTime() + 1 * 24 * 60 * 60 * 1000)
    var theDayAfterTomorrow = new Date()
    theDayAfterTomorrow.setTime(new Date().getTime() + 2 * 24 * 60 * 60 * 1000)
    // 展示的5个可选日期 -- okokok
    this.setData({
      DateToBackground: [
        (theDayBeforeYesterday.getFullYear() + "-" + (theDayBeforeYesterday.getMonth() + 1) + "-" + theDayBeforeYesterday.getDate()),
        (yesterday.getFullYear() + "-" + (yesterday.getMonth() + 1) + "-" + yesterday.getDate()), (today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate()), (tomorrow.getFullYear() + "-" + (tomorrow.getMonth() + 1) + "-" + tomorrow.getDate()),
        (theDayAfterTomorrow.getFullYear() + "-" + (theDayAfterTomorrow.getMonth() + 1) + "-" + theDayAfterTomorrow.getDate())
      ]
    })
    this.setData({
      Date: [(this.translateMonth((theDayBeforeYesterday.getMonth() + 1)) + "\n" + theDayBeforeYesterday.getDate()), (this.translateMonth((yesterday.getMonth() + 1)) + " " + yesterday.getDate()), (this.translateMonth((today.getMonth() + 1)) + " " + today.getDate()), (this.translateMonth((tomorrow.getMonth() + 1)) + " " + tomorrow.getDate()), (this.translateMonth((theDayAfterTomorrow.getMonth()) + 1) + " " + theDayAfterTomorrow.getDate())]
    })
    this.setData({
      Day: [this.translateDay(theDayBeforeYesterday), this.translateDay(yesterday), this.translateDay(today), this.translateDay(tomorrow), this.translateDay(theDayAfterTomorrow), ]
    })
    this.setData({
      month: (today.getMonth() + 1)
    });
    this.translateMonth(this.data.month);

    //首次进入加载当天数据
    this.getMenuList_first();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.fromOrder) {
      // 订单页操作后返回需要刷新
      this.getMenuList_first();
      this.setData({
        fromOrder: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 食堂切换
  swichNav: function (e) {
    var cur = e.target.dataset.current; //查询标题序号
    if (this.data.currentTab != cur) {
      let foodType = JSON.parse(JSON.stringify(this.data.foodType1))
      this.setData({
        currentTab: cur,
        foodType: cur == 2 ? foodType : foodType.slice(0, 2),
        foodTotalCount: 0,
        foodTotalAmount: 0
      })
      this.handleFoodTypeIndex()
      this.getMenuList()
    }
  },
  // 日期切换   和食堂切换代码可以合并，没时间了，先不改
  swichNavDate: function (e) {
    var cur = e.target.dataset.current; //查询标题序号
    if (this.data.currentTabDate != cur) {
      let foodType = JSON.parse(JSON.stringify(this.data.foodType1))
      this.setData({
        currentTabDate: cur,
        foodType: this.data.currentTab != 1 ? foodType : foodType.slice(0, 2),
        foodTotalCount: 0,
        foodTotalAmount: 0
      })
      this.getMenuList()
    }
  },
  // 获取周
  translateDay: function (e) {
    //计算周几
    var weekDate = e.getDay()
    if (weekDate == 1) {
      weekDate = "一"
    }
    if (weekDate == 2) {
      weekDate = "二"
    }
    if (weekDate == 3) {
      weekDate = "三"
    }
    if (weekDate == 4) {
      weekDate = "四"
    }
    if (weekDate == 5) {
      weekDate = "五"
    }
    if (weekDate == 6) {
      weekDate = "六"
    }
    if (weekDate == 0) {
      weekDate = "日"
    }
    //设置日期
    return "星期" + weekDate
  },
  // 获取月份
  translateMonth: function (e) {
    if (e == 1) {
      return "Jan"
    }
    if (e == 2) {
      return "Feb"
    }
    if (e == 3) {
      return "Mar"
    }
    if (e == 4) {
      return "Apr"
    }
    if (e == 5) {
      return "May"
    }
    if (e == 6) {
      return "Jun"
    }
    if (e == 7) {
      return "Jul"
    }
    if (e == 8) {
      return "Aug"
    }
    if (e == 9) {
      return "Sept"
    }
    if (e == 10) {
      return "Oct"
    }
    if (e == 11) {
      return "Nov"
    }
    if (e == 12) {
      return "Dec"
    }
  },
  // 餐厅意见收集
  goToComment: function (e) {
    //计算当月第一天
    var thisMonth = new Date().getMonth() + 1
    var thisYear = new Date().getFullYear()
    var firstDay = thisYear + "-" + thisMonth + "-" + "01"
    wx.navigateTo({
      url: "/pages/comment/comment?firstDay=" + firstDay
    })
  },
  // 餐品详情
  goToFoodComment: function (e) {
    //计算当月第一天
    var thisMonth = new Date().getMonth() + 1
    var thisYear = new Date().getFullYear()
    var firstDay = thisYear + "-" + thisMonth + "-" + "01"
    var dish_id = this.data.foodList[this.data.foodTypeIndex][e.currentTarget.dataset.index].dish_id;
    var name = this.data.foodList[this.data.foodTypeIndex][e.currentTarget.dataset.index].name;
    var canteen = this.data.foodList[this.data.foodTypeIndex][e.currentTarget.dataset.index].canteen;
    var meal = this.data.foodList[this.data.foodTypeIndex][e.currentTarget.dataset.index].meal;
    var description = this.data.foodList[this.data.foodTypeIndex][e.currentTarget.dataset.index].description
    var price = this.data.foodList[this.data.foodTypeIndex][e.currentTarget.dataset.index].price
    let imgUrl = this.data.foodList[this.data.foodTypeIndex][e.currentTarget.dataset.index].imgUrl
    let voteData = {
      menuDate: this.data.DateToBackground[this.data.currentTabDate],
      dishID: dish_id,
      canteenid: this.data.currentTab,
      dishName: name
    }
    wx.setStorage({
      data: JSON.stringify(voteData),
      key: 'voteData',
    })
    wx.navigateTo({
      url: "/pages/foodcomment/foodcomment?firstDay=" + firstDay + "&dish_id=" + dish_id + "&foodName=" + name + "&canteen=" + canteen + "&meal=" + meal + "&description=" + description + "&price=" + price + "&imgUrl=" + imgUrl
    })
  },
  handleFoodTypeIndex: function () {
    //此处计算时间，展示当前时间段meal
    if (this.data.currentTab != 1) {
      if (new Date().getHours() > 0 && new Date().getHours() < 9) {
        this.setData({
          foodTypeIndex: 0
        })
      } else if (new Date().getHours() > 9 && new Date().getHours() <13) {
        this.setData({
          foodTypeIndex: 1
        })
      } else {
        this.setData({
          foodTypeIndex: 2
        })
      }
    } else {
      if (new Date().getHours() > 0 && new Date().getHours() < 9) {
        this.setData({
          foodTypeIndex: 0
        })
      } else {
        this.setData({
          foodTypeIndex: 1
        })
      }
    }
  },
  //首次加载菜品数据请求，按时间段区分默认显示meal
  getMenuList_first: function (e) {
    this.isAbleOrder()
    this.handleFoodTypeIndex()
    let _this = this
    // let url = this.data.currentTab == 3 ? api.canteen3 : api.canteen
    let url = api.canteen
    //请求菜单数据
    wx.request({
      // url: "https://542124141.xyz/pam/menu/getList?menu_date=" + this.data.DateToBackground[this.data.currentTabDate] + "&canteen_id=" + this.data.currentTab + "&pageSize=999",
      url: url + "?menu_date=" + this.data.DateToBackground[this.data.currentTabDate] + "&canteen_id=" + this.data.currentTab + "&pageIndex=1&pageSize=9999",
      method: "GET",
      success(res) {
        if (res.data.state == 1) {
          let data = res.data.data
          //是否展示无菜品图片
          if (data.total == 0) {
            _this.setData({
              emptyHidden: false
            })
          } else {
            //按价格排序
            data.list.sort(function(a,b){
              return(b.price-a.price)
            })
            let breakfastList = [],
              lunchList = [],
              dinnerList = [];
            data.list.forEach((item, index) => {
              let listItem = {
                name: item.name,
                dish_id: item.dish_id ? item.dish_id : item.id,
                canteen: item.canteen_id == 1 ? '主办一楼' : item.canteen_id == 2 ? '主办东六楼' : '第二办公区',
                // meal: item.meal == 0 ? '早餐' : item.meal == 1 ? '午餐' : item.meal == 2 ? '晚餐' : '',
                meal: item.meal,
                description: item.description ? item.description : item.style ? item.style : '--',
                price: item.price ? item.price : '--',
                imgUrl: item.imgUrl ? item.imgUrl : '/images/pic_defaultFood.png',
                count: item.count ? item.count : 0,
                label: 0
              }
              if (item.meal == 0) {
                breakfastList.push(listItem)
              } else if (item.meal == 1) {
                lunchList.push(listItem)
              } else if (item.meal == 2) {
                dinnerList.push(listItem)
              }
            })
            // let foodList = [breakfastList, lunchList, dinnerList]
            let foodList = _this.data.currentTab != 1 ? [breakfastList, lunchList, dinnerList] : [breakfastList, lunchList]
            _this.setData({
              emptyHidden: true,
              foodList: foodList
            })
            if (_this.data.currentTab == 3) _this.getEcho()
          }
        }
      }
    })
  },
  //加载菜品数据请求
  getMenuList: function (e) {
    this.setData({ foodList: [] })
    this.isAbleOrder()
    //此处计算时间，展示当前时间段meal
    // this.setData({
    //   foodTypeIndex: 0
    // })
    let _this = this
    // let url = this.data.currentTab == 3 ? api.canteen3 : api.canteen
    let url = api.canteen
    //请求菜单数据
    wx.request({
      // url: "https://542124141.xyz/pam/menu/getList?menu_date=" + this.data.DateToBackground[this.data.currentTabDate] + "&canteen_id=" + this.data.currentTab + "&pageSize=999",
      url: url + "?menu_date=" + this.data.DateToBackground[this.data.currentTabDate] + "&canteen_id=" + this.data.currentTab + "&pageIndex=1&pageSize=9999",
      method: "GET",
      success(res) {
        if (res.data.state == 1) {
          let data = res.data.data
          // console.log(data)
          //是否展示无菜品图片
          if (data.total == 0) {
            _this.setData({
              emptyHidden: false
            })
          } else {
                        //按价格排序
            data.list.sort(function(a,b){
              return(b.price-a.price)
            })
            let breakfastList = [],
              lunchList = [],
              dinnerList = [];
            data.list.forEach((item, index) => {
              let listItem = {
                name: item.name,
                dish_id: item.dish_id ? item.dish_id : item.id,
                canteen: item.canteen_id == 1 ? '燎源' : item.canteen_id == 2 ? '福荫' : '江茂源',
                // meal: item.meal == 0 ? '早餐' : item.meal == 1 ? '午餐' : item.meal == 2 ? '晚餐' : '',
                meal: item.meal,
                description: item.description ? item.description : item.style ? item.style : '--',
                price: item.price ? item.price : '--',
                imgUrl: item.imgUrl ? item.imgUrl : '/images/pic_defaultFood.png',
                count: item.count ? item.count : 0,
                label: 0
              }
              if (item.meal == 0) {
                breakfastList.push(listItem)
              } else if (item.meal == 1) {
                lunchList.push(listItem)
              } else if (item.meal == 2) {
                dinnerList.push(listItem)
              }
            })
            // let foodList = [breakfastList, lunchList, dinnerList]
            let foodList = _this.data.currentTab != 1 ? [breakfastList, lunchList, dinnerList] : [breakfastList, lunchList]
            console.log(foodList)
            _this.setData({
              emptyHidden: true,
              foodList: foodList
            })
            if (_this.data.currentTab == 3) _this.getEcho()
          }
        }
      }
    })
  },
  getEcho: function (e) {
    let _this = this
    wx.request({
      url: api.echo + "?menu_date=" + this.data.DateToBackground[this.data.currentTabDate],
      method: "GET",
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success(res) {
        if (res.data.state == 1) {
          let data = res.data.data
          // console.log(data)
          let count = data.count && data.count.indexOf('/') > 0 ? data.count.split('/') : [data.count]
          let indent = data.indent && data.indent.indexOf('/') > 0 ? data.indent.split('/') : [data.indent]
          let foodList = _this.data.foodList
          let foodType = JSON.parse(JSON.stringify(_this.data.foodType1))
          let foodTotalAmount = 0
          indent.forEach((item, index) => {
            foodList.forEach((jtem, jndex) => {
              jtem.forEach((ktem, kndex) => {
                if (item == ktem.dish_id) {
                  foodType[ktem.meal].count +=  count[index] * 1
                  ktem.label = count[index]
                  ktem.count = count[index]
                  foodTotalAmount += count[index] * ktem.price
                }
              })
            })
          })
          _this.setData({
            foodType: _this.data.currentTab != 1 ? foodType : foodType.slice(0, 2),
            foodList: foodList,
            foodTotalCount: foodType[0].count + foodType[1].count,
            foodTotalAmount: foodTotalAmount,
            canteenOrderId: data.id
          })
        }
      }
    })
  },
  binderrorImg: function (e) {
    let foodList = this.data.foodList
    foodList[this.data.foodTypeIndex][e.currentTarget.dataset.index].imgUrl = '/images/pic_defaultFood.png'
    this.setData({
      foodList: foodList
    })
  },
  // 三餐切换
  ToggleFoodType: function (e) {
    this.setData({
      foodTypeIndex: e.currentTarget.dataset.index
    })
  },
  // 加、减
  handleCount: function (e) {
    if (this.data.isAble) {
      let foodList = this.data.foodList
      let foodType = this.data.foodType
      let foodTotalAmount = this.data.foodTotalAmount
      let action = e.currentTarget.dataset.action, index = e.currentTarget.dataset.index, meal = e.currentTarget.dataset.meal;
      if (action == 'add') {
        foodList[meal][index].count ++
        foodType[meal].count ++
        foodTotalAmount += foodList[meal][index].price
      } else if (action == 'minus') {
        foodList[meal][index].count --
        foodType[meal].count --
        foodTotalAmount -= foodList[meal][index].price
      }
      this.setData({
        foodList: foodList,
        foodType: foodType,
        foodTotalCount: foodType[0].count + foodType[1].count,
        foodTotalAmount: foodTotalAmount
      })
      if (this.data.foodTotalCount <= 0) {
        this.setData({
          dialogShow: false
        })
      }
    } else {
      this.setData({
        tipsDialog: true,
        tipsContent: '不能预定当天套餐或者 ' + this.data.deadline + ' 后不能预定第二天套餐'
      })
    }
  },
  isDialogShow: function (e) {
    if (this.data.isAble) {
      if (this.data.foodTotalCount > 0) {
        this.setData({
          dialogShow: e.currentTarget.dataset.show == 'true' ? true : false
        })
      }
    } else {
      this.setData({
        tipsDialog: true,
        tipsContent: '不能预定当天套餐或者 ' + this.data.deadline + ' 后不能预定第二天套餐'
      })
    }
  },
  // 是否可订餐
  isAbleOrder: function () {
    let _this = this
    // 获取订餐截止时间
    wx.request({
      url: api.getOrderDeadline,
      method: "GET",
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success(res) {
        if (res.data.state == 1) {
          let selectDate = _this.data.DateToBackground[_this.data.currentTabDate]
          // console.log(new Date(selectDate).getTime())  // 2022-6-1 00:00:00
          let currentDate = new Date()
          // 小程序不识别时间-，只能用/
          let diffValue = new Date(selectDate.replace(/-/g, '/') + ' ' + res.data.data).getTime() - currentDate.getTime()
          if (diffValue < 24*60*60*1000) {
            _this.setData({
              deadline: res.data.data,
              isAble: false
            })
          } else {
            _this.setData({
              deadline: res.data.data,
              isAble: true
           })
          }
        }
      }
    })


    // let selectDate = this.data.DateToBackground[this.data.currentTabDate]
    // console.log(this.data.deadline)
    // // console.log(new Date(selectDate).getTime())  // 2022-6-1 00:00:00
    // let currentDate = new Date()
    // // 小程序不识别时间-，只能用/
    // let diffValue = new Date(selectDate.replace(/-/g, '/') + ' 20:00:00').getTime() - currentDate.getTime()
    // // console.log(diffValue)
    // if (diffValue < 24*60*60*1000) {
    //   this.setData({ isAble: false })
    // } else {
    //   this.setData({ isAble: true })
    // }
  },
  // 提交订餐
  handleOrder: function () {
    let indent = '', count = '', _this= this;
    this.data.foodList.forEach(item => {
      item.forEach(jtem => {
        if (jtem.count > 0) {
          indent += '/' + jtem.dish_id
          count += '/' + jtem.count
        }
      })
    })
    wx.request({
      url: api.orderFood,
      method: "POST",
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: {
        'id': this.data.canteenOrderId ? this.data.canteenOrderId : '',
        'menu_date': this.data.DateToBackground[this.data.currentTabDate],
        'canteen_id': this.data.currentTab,
        'indent': indent.slice(1),
        'count': count.slice(1)
      },
      success(res) {
        if (res.data.state == 1) {
          // 操作
          _this.getMenuList()
          // 重置操作是否可以放到getMenuList，切换日期、餐厅也需要，没有时间改了
          let foodType = JSON.parse(JSON.stringify(_this.data.foodType1))
          _this.setData({
            // foodType: foodType,
            dialogShow: false,
            // foodTotalCount: 0,
            // foodTotalAmount: 0,
            promptShow: true
          })
          setTimeout(() => {
            _this.setData({
              promptShow: false
            })
          }, 3000)
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'error',
          })
        }
      }
    })
  },
  // 订餐提示
  handleTipsDialog: function (e) {
    this.setData({
      tipsDialog: e.currentTarget.dataset.flag == 'true' ? true : false,
      tipsContent: '如有建议或问题请联系新中监管人员（欧阳胜 17727992787 26669434/8434）'
    })
  },
  goOrder: function () {
    wx.setStorage({
      key: 'orderList',
      data: JSON.stringify(this.data.foodList)
    })
    wx.navigateTo({
      url: "/pages/order/order?id=" + this.data.canteenOrderId + '&menu_date=' + this.data.DateToBackground[this.data.currentTabDate] + '&isAble=' + this.data.isAble + '&deadline=' + this.data.deadline
    })
  },
  // 返回上一层
  goBack: function (e) {
    wx.navigateBack({
      delta: 1,
    })
  }
})